package com.lagou.config;

import com.lagou.bean.Configuration;
import com.lagou.bean.MapperStatement;
import com.lagou.io.Resources;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class XMLConfigerBuilder {
    private Configuration conf;

    public XMLConfigerBuilder() {
        this.conf = new Configuration();
    }

    public Configuration parseConf(InputStream stream) throws Exception {
        Document document = new SAXReader().read(stream);
        Element rootElement = document.getRootElement();

        //首先是解析property标签下的属性,获取数据库连接
        List<Element> propertyElements =
                rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element propertyElement : propertyElements) {
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");
            properties.setProperty(name,value);
        }

        //开始给config对象设置datasource
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driver"));
        dataSource.setUser(properties.getProperty("user"));
        dataSource.setPassword(properties.getProperty("password"));
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        conf.setDataSource(dataSource);

        Map<String, MapperStatement> allMappers = conf.getMappers();

        List<Element> mapperEle = rootElement.selectNodes("//mapper");
        for (Element item : mapperEle) {
            String path = item.attributeValue("resource");
            InputStream mapperStream = Resources.getResource(path);
            XMLMapperBuilder mapperBuilder = new XMLMapperBuilder();
            //每个mapper.xml文件，对应多个MapperStatement对象，最终把他们合并到一起。
            Map oneMapper = mapperBuilder.parse(mapperStream);
            allMappers.putAll(oneMapper);
        }

        return conf;
    }

}
